﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using RookieLibSharp.Configuration;
using BirthdayRemainder.Forms;
using BirthdayRemainder.Model;
using RookieLibSharp.Progress;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using RookieLibSharp.WinApi;
using RookieLibSharp.Security;
namespace BirthdayRemainder
{

    public class SftMgr
    {
        /// <summary>
        /// 父窗口句柄
        /// </summary>
        private IntPtr ParantHwnd;
        /// <summary>
        /// 后台线程
        /// </summary>
        Thread ThdBack;
        public SftMgr(IntPtr parentHwnd)
        {
            Funcs.InitPubVal();
            ParantHwnd = parentHwnd;
            ProgressManager.SetHwnd(this.ParantHwnd);
#if DEBUG
            GlobalValue.regRsult = RegisterResult.SUCCEED;
#else
            GlobalValue.regRsult = GlobalValue.sftReg.RegResult;
#endif
            //保存注册情况，每次启动都保存
            Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_REGISTER, GlobalValue.regRsult == RegisterResult.SUCCEED);
            ThdBack = new Thread(BackgroundProc);
        }
        /// <summary>
        /// 退出程序接受后台线程
        /// </summary>
        public void Abort()
        {
            if ((ThdBack != null) &&(ThdBack.IsAlive))
            {
                ThdBack.Abort();
            }
            ThdBack = null;
            DbClose();
        }
        /// <summary>
        /// 执行后台线程
        /// </summary>
        public void RunBackgroundProc()
        {
            ThdBack.Start();
        }
        /// <summary>
        /// 后台线程
        /// </summary>
        private void BackgroundProc()
        {
            InitLstView();
            if (NeedCheckUpdate())
            {
                CheckUpdate(false);
            }
            SetDisHasNewVersion(Cfg.ReadBool(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_HAS_NEW_VERSION, false));
        }
        /// <summary>
        /// 发送消息初始化
        /// </summary>
        public void InitLstView()
        {
            Win32Api.SendMessage(ParantHwnd, (int)WM_MSG.WM_MSG_LIST_INIT, IntPtr.Zero, IntPtr.Zero);
        }
        /// <summary>
        /// 显示添加窗体
        /// </summary>
        public void ShowAddInfo()
        {
            using (FrmAddInfo frm = new FrmAddInfo())
            {
                frm.ParantHwnd = ParantHwnd;
                frm.ShowDialog();
            }
        }
        /// <summary>
        /// 显示修改窗体
        /// </summary>
        /// <param name="name">修改的名称</param>
        /// <returns>修改后的名称</returns>
        public string ShowModify(string name)
        {
            using (FrmModify frm = new FrmModify(name))
            {
                frm.ShowDialog();
                return frm.ModifyName;
            }
        }
        /// <summary>
        /// 显示设置窗口
        /// </summary>
        public SetReturn ShowSet()
        {
            using (FrmSet frm = new FrmSet())
            {
                frm.ShowDialog();
                SetReturn setRet;
                setRet.RefreshList = frm.NeedRefreshList;
                setRet.RefreshBackColor = frm.NeedRefreshBackColor;
                return setRet;
            }
        }
        /// <summary>
        /// 判断配置文件是否存在
        /// </summary>
        /// <returns>TRUE 存在，否则不存在</returns>
        public bool CfgFileNameExist()
        {
            string cfgPath;
            Cfg.GetCfgPath(out cfgPath);
            return File.Exists(cfgPath);
        }
#region Database
        /// <summary>
        /// 获取全部信息，用以初始化界面
        /// </summary>
        /// <returns></returns>
        public static List<PersonInfo> DbGetAllInfo()
        {
            string[] ArrName = DbGetAllName();
            ProgressManager.UpdateStringInfo("初始化数据");
            List<PersonInfo> Lst = new List<PersonInfo>();
            if (ArrName != null)
            {
                ProgressManager.Init(0, "初始化数据", ArrName.Length);
                for (int idx = 0; idx < ArrName.Length; idx++)
                {
                    PersonInfo info = DbGetRecord(ArrName[idx]);
                    Lst.Add(info);
                    ProgressManager.UpdateVale(0);
                }
            }

            Lst.Sort(new PersonInfoComparer());
            return Lst;
        }
        /// <summary>
        /// 获取全部名称
        /// </summary>
        /// <returns></returns>
        public static string[] DbGetAllName()
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.GetAllNames();
        }
        /// <summary>
        /// 添加一个姓名
        /// </summary>
        /// <param name="name">姓名字符串</param>
        /// <returns></returns>
        public bool DbAddName(string name)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.AddName(name);
        }
        /// <summary>
        /// 删除一个姓名
        /// </summary>
        /// <param name="name">姓名字符串</param>
        /// <returns></returns>
        public static bool DbDeleteName(string name)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.DeleteName(name);
        }
        /// <summary>
        /// 判断名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool DbNameIsExit(string name)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.NameIsExit(name);
        }
        /// <summary>
        /// 更新一个记录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool DbUpdateRecord(PersonInfo info)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.UpdateRecord(info);
        }
        /// <summary>
        /// 插入一个记录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool DbInsertRecord(PersonInfo info)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.InsertRecord(info);
        }
        /// <summary>
        /// 获取记录
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static PersonInfo DbGetRecord(string name)
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            return dbMgr.GetRecord(name);
        }
        /// <summary>
        /// 删除全部记录
        /// </summary>
        public static void DbDeleteAllRecord()
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            dbMgr.DeleteAllRecord();
        }
        private static void DbClose()
        {
            DbMgr dbMgr = DbMgr.GetDbMgr();
            dbMgr.CloseDatabase();
        }
        /// <summary>
        /// 批量导入数据
        /// </summary>
        public bool ShowImportData()
        {
            using (FrmImportData frm = new FrmImportData())
            {
                frm.ShowDialog();
                return frm.IsImportData;
            }
        }
        public void ShowExportData()
        {
            using (FrmExportData frm = new FrmExportData())
            {
                frm.ShowDialog();
            }
        }
        private bool NeedCheckUpdate()
        {
            if (Funcs.IsANewDay())
            {
                return true;
            }
            return false;
        }
        public SoftwareUpdateInfor CheckUpdate(bool bForced)
        {
            SoftwareUpdateInfor updateInfo = new SoftwareUpdateInfor(GlobalValue.SOFT_INFO_URL,Funcs.GetSftVersion());
            if (updateInfo.NeedUpdate)
            {
                GlobalValue.SftwareDownloadUrl = updateInfo.UpdateUrl;
            }
            SetDisHasNewVersion(updateInfo.NeedUpdate);
            return updateInfo;
        }
        public void SetDisHasNewVersion(bool bHasNewVersion)
        {
            Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_HAS_NEW_VERSION, bHasNewVersion);
            Win32Api.SendMessage(ParantHwnd, (int)WM_MSG.WM_MSG_HAS_UPDATE, IntPtr.Zero, IntPtr.Zero);

        }
#endregion


#region Menu

        public void ShowHelpAdvice()
        {
            using (FrmGiveAdvice frm = new FrmGiveAdvice())
            {
                frm.ShowDialog();
            }
        }
        public string GetAboutMe()
        {
            return string.Format("版本号：V{0}\n作者：我是菜鸟\n邮箱：raoqiangnihao@126.com\n\n如有意见和建议请与作者联系\n 菜单中点击【帮助】按钮并选择【意见和建议】，谢谢",Funcs.GetSftVersion());
        }
        public void ShowRegForm()
        {
            using (RegisterUI frm = new RegisterUI(GlobalValue.sftReg))
            {
                frm.ShowDialog();
                GlobalValue.regRsult = GlobalValue.sftReg.RegResult;
            }
            //注册后保存
            Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_REGISTER, GlobalValue.regRsult == RegisterResult.SUCCEED);
        }
#endregion
    }
}
